/*
 * ChartService.groovy
 * Author: Khang
 * Last Update: 11/07/2013
 * Purpose: use for Burndown chart
 *
 * */
package com.ant.myagile
import com.ant.myagile.IssueService
class ChartService {
	
	IssueService issueService = new IssueService()
	PointRemainService pointRemainService = new PointRemainService()
	CommonService commonService= new CommonService()
	
	//Get Chart data by sprintID
    def getDataChartBySprint(SprintID) {
		Hashtable<String, Integer> htBug= new Hashtable<String, Integer>()
		//Get all bugs
		def bugs=issueService.findBugBySprintId(SprintID)
		println bugs
		for(bug in bugs)
		{
			def pointRemains= pointRemainService.findPointRemainByIssue(bug.id)
			for(pointRemain in pointRemains)
			{
				def rPoint=commonService.ConvertPoint(pointRemain.pointRemain)
				if(htBug.containsKey(pointRemain.dateUpdate))
				{
					int value=htBug.get(pointRemain.dateUpdate).toInteger()
					if(rPoint!=0)
						htBug.put(pointRemain.dateUpdate,value+1)
					else
						htBug.put(pointRemain.dateUpdate,value-1)
				}
				else 
				{
					if(rPoint!=0)
						htBug.put(pointRemain.dateUpdate, 1)
				}
			}
		}
		Map mapBug = new TreeMap(htBug)
		
		Hashtable<String, ArrayList<Integer>> ht= new Hashtable<String, ArrayList<Integer>>()
		def issues=issueService.findIssueBySprintId(SprintID)
		for(issue in issues)
		{
			def pointRemains= pointRemainService.findPointRemainByIssue(issue.id)
			for(pointRemain in pointRemains)
			{
				def rPoint=commonService.ConvertPoint(pointRemain.pointRemain)
				ArrayList<Integer> arr= new ArrayList<Integer>()
				if(ht.containsKey(pointRemain.dateUpdate))
				{
					arr=ht.get(pointRemain.dateUpdate)
				}
				arr.add(rPoint)
				ht.put(pointRemain.dateUpdate, arr)
			}
		}
		//Sort hasttable
		Map map = new TreeMap(ht)
		//Create date list
		def dList=map.keySet()
		//Create point list and issue list
		def pList=new ArrayList<Integer>()
		def iList=new ArrayList<Integer>()
		def bList=new ArrayList<Integer>()
		def resultTest=new ArrayList<ArrayList<Integer>>()
		for(date in dList)
		{
			ArrayList<Integer> arrPoint=map.get(date)
			def Rpoint=0
			def countIssue=0
			for(p in arrPoint)
			{
				Rpoint+=p
				if(p!=0)
					countIssue++
			}
			pList.add(Rpoint)
			iList.add(countIssue)
			resultTest.add(arrPoint)
			
			//check date have bug?
			if(htBug.containsKey(date))
				bList.add(htBug.get(date))
			else
				bList.add(0)
		}
		
		return [dList : dList, pList: pList, iList:iList, resultTest:resultTest, bList:bList]
    }
}
